/*
 * @lc app=leetcode.cn id=1008 lang=typescript
 *
 * [1008] 前序遍历构造二叉搜索树
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function bstFromPreorder(preorder: number[]): TreeNode | null {
  const build = (order: number[], l: number, r: number): TreeNode | null => {
    if (l > r) return null;
    let index = l + 1;
    // 找到右子树的位置
    while (index <= r && order[index] < order[l]) index++;
    const root = new TreeNode(order[l]);
    root.left = build(preorder, l + 1, index - 1);
    root.right = build(preorder, index, r);
    return root;
  };

  return build(preorder, 0, preorder.length - 1);
}
// @lc code=end
